package com.todo.pro.controller;

import java.math.BigDecimal;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.todo.pro.entity.User;
import com.todo.pro.entity.WxUser;
import com.todo.pro.enums.UserDefaultHeadEnum;
import com.todo.pro.req.model.WeiXinBindModel;
import com.todo.pro.req.model.WeiXinLoginModel;
import com.todo.pro.service.UserService;
import com.todo.pro.service.WxUserService;
import com.todo.pro.util.AesUtil;
import com.todo.pro.util.EmojiUtils;
import com.todo.pro.web.domain.AjaxResult;
import com.todo.pro.weixin.WeiXinUtils;
import com.xiaoleilu.hutool.date.DateUtil;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author SiZhongxia
 * @since 2017-12-27
 */
@Controller
@RequestMapping("/weixin")
public class WeiXinController {

	@Autowired
	private WeiXinUtils weiXinUtils;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private UserService userService;

	@ResponseBody
	@RequestMapping(value = { "/login" })
	public AjaxResult login(@RequestBody(required = true) WeiXinLoginModel requestModel) {
		String code = requestModel.getCode();
		// 获取到OPENID
		JSONObject wxJson = weiXinUtils.getMpInfoByCode(code);
		if (wxJson == null) {
			return AjaxResult.error("获取微信用户标识失败，请稍候重试!!!");
		}
		String openId = wxJson.getString("openid");
		if (StringUtils.isBlank(openId)) {
			return AjaxResult.error(wxJson.toJSONString());
		}
		String sessionKey = wxJson.getString("session_key");
		if (StringUtils.isBlank(sessionKey)) {
			return AjaxResult.error(wxJson.toJSONString());
		}

		Wrapper<WxUser> wxUserWrapper = new EntityWrapper<>();
		wxUserWrapper.eq("open_id", openId);
		WxUser wxUser = wxUserService.selectOne(wxUserWrapper);
		User user = null;
		if (wxUser == null) {
			// 创建用户
			user = createUser();
			userService.insert(user);
			// 创建微信关联
			wxUser = createWxUser(user.getId(), openId, sessionKey);
			wxUserService.insert(wxUser);
		} else {
			user = userService.selectById(wxUser.getUserId());
		}

		if (user == null) {
			return AjaxResult.error("获取用户信息失败，请稍候重试!!!");
		}

		return AjaxResult.success().put("token", AesUtil.encryptHex(user.getId().toString())).put("openId", openId)
				.put("hadAuth", user.getBindWxmpFlag().intValue() == 1).put("userHeadPic", user.getUserHeadPic())
				.put("userName", user.getUserName()).put("canCreate", user.getCanCreate().intValue() == 1);
	}

	private User createUser() {
		User user = new User();
		user.setUserName("微信用户");
		user.setUserPhoneNo("");
		user.setUserHeadPic(UserDefaultHeadEnum.getRandom());
		user.setPassword("");
		user.setBindWxgzhFlag(0);
		user.setBindWxmpFlag(0);
		user.setFinishRate(new BigDecimal("100"));
		user.setRegistTime(DateUtil.date());
		user.setLastLoginTime(DateUtil.date());
		return user;
	}

	/**
	 * @param userId
	 * @param openId
	 * @return
	 */
	private WxUser createWxUser(Long userId, String openId, String sessionKey) {
		WxUser wxUser = new WxUser();
		wxUser.setUserId(userId);
		wxUser.setOpenId(openId);
		wxUser.setUnionId("");
		wxUser.setSessionKey(sessionKey);
		wxUser.setNickName("");
		wxUser.setAvatarUrl("");
		wxUser.setGender(0);
		wxUser.setCountry("");
		wxUser.setCity("");
		wxUser.setProvince("");
		wxUser.setLanguage("");
		wxUser.setCreateTime(DateUtil.date());
		return wxUser;
	}

	@ResponseBody
	@RequestMapping(value = { "/bind" })
	public AjaxResult bind(@RequestBody(required = true) WeiXinBindModel requestModel) {
		String token = requestModel.getToken();
		if (StringUtils.isBlank(token)) {
			return AjaxResult.error("请求失败，无效的数据 E1");
		}
		String userId = AesUtil.decryptStr(token);
		if (userId == null) {
			return AjaxResult.error("请求失败，无效的数据 E3");
		}

		User user = userService.selectById(new Long(userId));
		if (user == null) {
			return AjaxResult.error("请求失败，无效的数据 E4");
		}

		Wrapper<WxUser> wxUserWrapper = new EntityWrapper<>();
		wxUserWrapper.eq("user_id", user.getId());
		WxUser wxUser = wxUserService.selectOne(wxUserWrapper);
		if (wxUser == null) {
			return AjaxResult.error("请求失败，无效的数据 E5");
		}

		if (!wxUser.getUserId().equals(user.getId())) {
			return AjaxResult.error("请求失败，无效的数据 E6");
		}

		if (StringUtils.isBlank(requestModel.getNickName())) {
			return AjaxResult.error("请求失败，无效的数据 E7");
		}

		if (StringUtils.isBlank(requestModel.getAvatarUrl())) {
			return AjaxResult.error("请求失败，无效的数据 E8");
		}

		wxUser.setNickName(EmojiUtils.parseToAliases(requestModel.getNickName()));
		wxUser.setAvatarUrl(requestModel.getAvatarUrl());
		wxUser.setGender(requestModel.getGender());
		wxUser.setProvince(requestModel.getProvince());
		wxUser.setCountry(requestModel.getCountry());
		wxUser.setCity(requestModel.getCity());
		wxUser.setLanguage(requestModel.getLanguage());
		if (!wxUserService.updateById(wxUser)) {
			return AjaxResult.error("请求失败，更新数据失败 E9");
		}

		user.setUserHeadPic(requestModel.getAvatarUrl());
		user.setUserName(EmojiUtils.parseToAliases(requestModel.getNickName()));
		user.setBindWxmpFlag(1);
		if (!userService.updateById(user)) {
			return AjaxResult.error("请求失败，更新数据失败 E10");
		}

		return AjaxResult.success();
	}

}
